#/bin/sh

cd mods/

clean_added_jars() {
	for i in *.jar.added; do 
		mv -- "$i" "${i%%.added}"
	done
}

clean_added_jars

echo "==========================="
echo "Processing mods/"
echo "==========================="
for file in *.toml; do
	echo
	echo "Processing $file"

	download_mode="$(grep 'mode' < "$file" | cut -d' ' -f3)"
	# remove double quotes
	download_mode="${download_mode#\"}"
	download_mode="${download_mode%\"}"

	filename="$(grep 'filename' < "$file" | cut -d' ' -f3-)"
	# remove double quotes
	filename="${filename#\"}"
	filename="${filename%\"}"

	if [ "$download_mode" = 'metadata:curseforge' ]; then
		file_id="$(grep 'file-id' < "$file" | cut -d' ' -f3)"
		# remove double quotes
		file_id="${file_id#\"}"
		file_id="${file_id%\"}"

		url="https://edge.forgecdn.net/files/$(printf '%s' "$file_id" | cut -c1-4)/$(printf '%s' "$file_id" | cut -c5-7)/$filename"
	else
		url="$(grep 'url' < "$file" | cut -d' ' -f3)"
		# remove double quotes
		url="${url#\"}"
		url="${url%\"}"
	fi

	if [ -e "$filename" ]; then
		echo "$filename exists, skipping..."
	else
		echo "$filename from $url"
		curl -L "$url" -o "$filename"
	fi
	mv "$filename" "${filename}.added"
done

printf 'Processed %s .jar files and %s .pw.toml files\n' "$(ls *.jar.added | wc --lines)" "$(ls *.pw.toml | wc --lines)"
echo "Unrecognized JAR files:"
ls *.jar
clean_added_jars
